import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { DatePipe } from '@angular/common';
import { ActivatedRoute } from '@angular/router';
import { NzModalService } from 'ng-zorro-antd/modal';
import { CustomizedCouponService } from '../services/customized-coupon.service';

@Component({
  selector: 'app-customized-coupon-edit',
  templateUrl: './customized-coupon-edit.component.html',
  styleUrls: ['./customized-coupon-edit.component.scss'],
  providers: [DatePipe]
})
export class CustomizedCouponEditComponent implements OnInit {

  routeParams: any = {};
  formParams: any = {
    status: 5,
    type: 1, // 券类型 1：满减 2：折扣
    name: '', // 券名称
    remark: '', // 备注
    total: '', // 总数量
    orderLimitMoney: '', // 门槛（满多少）
    limitSmall: '', // 减免额度 or 折扣力度 or 优惠金额最小值
    limitBig: '', // 最高加价金额

    userType: 0, // 适用用户 0：不限制 1：C端 2：B端
    isShowWeb: 1, // 前端展示 0：不展示 1：展示
    getBeginTime: '', // 可领取开始时间
    getEndTime: '', // 可领取结束时间
    
    limitTimeNum: 0, // 限制使用 xx天 0：当天 1：明天
    useBeginTime: '', // 有效期使用开始时间
    useEndTime: '', // 有效期使用结束时间
    useDesc: '', // 使用说明

    // applyColour: '', // 适用成色 0：全部 1：二手 2：准新
    // containsModel: '', // 机型list 0：为全部 -1：为全不选
    containsTypes: '', // 适用品类

    remind: '0', // 过期N天提醒(参考优惠券、暂无用、用作提交)
    userLimitNum: '1', // 没人限领次数(参考优惠券、暂无用、用作提交)
    autoReverse: '0' // 每N天首次进店自动发放(参考优惠券、暂无用、用作提交)
  };

  // 可领取时间
  receiveDates: any[] = [];

  // 适用用户
  userTypeOptions: any = [
    {value: 0, label: '不限制'},
    {value: 2, label: 'B端'},
    {value: 1, label: 'C端'}
  ];

  // 适用品类
  categoryOptions: any = [];
  selectedCategory: any = [];

  // 有效时间
  effectiveDates: any[] = [];
  effectiveType: number = 1;

  // 审核 Modal
  isExamineVisible = false;
  examineParams = {
    remark: ''
  };

  submitReviewLoading = false;
  examineLoading = false;
  submitFormLoading = false;

  constructor(
    private message: NzMessageService,
    private datePipe: DatePipe,
    private activatedRoute: ActivatedRoute,
    private modal: NzModalService,
    private services: CustomizedCouponService
  ) {
    activatedRoute.queryParams.subscribe((res: any) => {
      this.routeParams = res || {};
    })
  }

  async ngOnInit() {
    await this.loadAdzGoodTypeList();
    
    if (['1', '3'].includes(this.routeParams.type)) {
      this.loadDetailsData();
    }
  }

  // 查询适用品类
  async loadAdzGoodTypeList() {
    const {code, data, message}: any = await this.services.getAdzGoodTypeList();
    if (code === 0) {
      this.categoryOptions = data || [];
    } else {
      this.message.error(message);
    }
  }

  // 查询详情
  async loadDetailsData() {
    const messId = this.message.loading('数据加载中..', { nzDuration: 0 }).messageId;
    const {code, data, message}: any = await this.services.getCouponUpdateDetail(this.routeParams.id);
    this.message.remove(messId);

    if (code === 0) {
      this.formParams.status = data.status;
      this.formParams.type = data.type; // 券类型 1：满减 2：折扣
      this.formParams.name = data.name || ''; // 券名称
      this.formParams.useDesc = data.useDesc || ''; // 规则
      this.formParams.remark = data.remark || ''; // 券名称
      this.formParams.name = data.name || ''; // 备注
      this.formParams.total = data.total || ''; // 总数量
      this.formParams.orderLimitMoney = data.orderLimitMoney || ''; // 总数量
      this.formParams.limitSmall = data.limitSmall || ''; // 减免额度 or 折扣力度 or 优惠金额最小值
      this.formParams.limitBig = data.limitBig || ''; // 最高加价金额

      this.formParams.userType = data.userType; // 适用用户(领取人)
      this.formParams.getBeginTime = data.getBeginTime; // 可领取开始时间
      this.formParams.getEndTime = data.getEndTime; // 可领取结束时间
      this.receiveDates = data.isShowWeb == 1 ? [data.getBeginTime, data.getEndTime] : [];

      // 有效时间
      if (data.limitTimeNum === -1) {
        this.effectiveType = 2;
        this.formParams.useBeginTime = data.useBeginTime;
        this.formParams.useEndTime = data.useEndTime;
        this.effectiveDates = [data.useBeginTime, data.useEndTime];
      } else {
        this.effectiveType = 1;
        this.formParams.limitTimeNum = data.limitTimeNum;
      }

      if (data.containsTypes === '0') {
        this.selectedCategory = this.categoryOptions.map((item: any) => +item.groupId);
      } else {
        this.selectedCategory = data.containsTypes.split(',').map((m: any) => +m);
      }

      this.formParams.isShowWeb = data.isShowWeb; // 展示 or 不展示
    } else {
      this.message.error(message);
    }
  }

  // submit
  async submitForm(state?: number) {
    if (!this.isVerifForms()) {
      return
    }
    let params = {
      ...this.formParams,
      limitBig: this.isEmpty(this.formParams.limitBig) ? '0' : this.formParams.limitBig,
      limitTimeNum: this.effectiveType === 2 ? '-1' : this.formParams.limitTimeNum, // 有效期
      containsTypes: this.selectedCategory.length === this.categoryOptions.length ? '0' : this.selectedCategory.join(',')
    }
    state ? this.submitReviewLoading = true : this.submitFormLoading = true;

    let res: any;
    if (['0', '3'].includes(this.routeParams.type)) {
      // add
      params.status = 5;
      res = await this.services.addCouponData(params);
    } else {
      // edit
      if (state) {
        // 提交审核
        params.status = state;
      }
      res = await this.services.editCouponData(params, this.routeParams.id);
    }
    state ? this.submitReviewLoading = false : this.submitFormLoading = false;

    if (res.code === 0) {
      this.message.success('操作成功');
      this.back();
    } else {
      this.message.error(res.message);
    }
  }

  /**
   * ----------------------------------------------------------------
   * 验证
   * ----------------------------------------------------------------
   */
  isVerifForms() {
    if (this.isEmpty(this.formParams.name)) {
      this.message.warning('请输入优惠券名称');
      return false;
    } else if (this.isEmpty(this.formParams.useDesc)) {
      this.message.warning('请输入优惠券规则');
      return false;
    } else if (this.isEmpty(this.formParams.total)) {
      this.message.warning('请输入发放总量');
      return false;
    } else if (this.isEmpty(this.formParams.orderLimitMoney)) {
      this.message.warning('请输入使用门槛');
      return false;
    } else if (this.isEmpty(this.formParams.limitSmall) && this.formParams.type === 1) {
      this.message.warning('请输入减免额度');
      return false;
    } else if (this.isEmpty(this.formParams.limitSmall) && this.formParams.type === 2) {
      this.message.warning('请输入折扣力度');
      return false;
    } else if (this.isEmpty(this.formParams.limitBig) && this.formParams.type === 2) {
      this.message.warning('请输入最高减免');
      return false;
    } else if (!this.receiveDates.length && this.formParams.isShowWeb === 1) {
      this.message.warning('请选择可领取时间');
      return false;
    } else if ((this.effectiveType === 1 && this.isEmpty(this.formParams.limitTimeNum)) || (this.effectiveType === 2 && !this.effectiveDates.length)) {
      this.message.warning('请输入有效期');
      return false;
    } else if (!this.selectedCategory.length) {
      this.message.warning('请选择适用品类');
      return false;
    } else {
      return true;
    }
  }

  // 门槛验证
  thresholdVerif() {
    if (this.formParams.orderLimitMoney && this.formParams.orderLimitMoney > 0) {
      switch (this.formParams.type) {
        case 1:
          // console.log('满减券');
          if (Number(this.formParams.limitSmall) && Number(this.formParams.limitSmall) > Number(this.formParams.orderLimitMoney)) {
            this.message.warning('使用门槛值需大于或等于减免额度值!');
            this.formParams.orderLimitMoney = '';
          }
          break;
        case 3:
          // console.log('随机券');
          if (this.formParams.limitSmall && this.formParams.limitBig) {
            let tempMax = Math.max.apply(Math, [this.formParams.limitSmall, this.formParams.limitBig]);
            if (tempMax > this.formParams.orderLimitMoney) {
              this.message.warning('使用门槛值需大于或等于优惠金额最大值!');
              this.formParams.orderLimitMoney = '';
            }
          }
          break;
      }
    }
  }

  // 减免金额验证(num：0--减免额度,1：最高减免金额)
  reductionVerif(num: number) {
    if (this.formParams.orderLimitMoney && this.formParams.orderLimitMoney > 0) {
      if (num == 0) {
        if (this.formParams.limitSmall && Number(this.formParams.limitSmall) > Number(this.formParams.orderLimitMoney)) {
          this.message.warning('减免额度值需小于或等于使用门槛值!');
          this.formParams.limitSmall = '';
        }
      } else {
        if (this.formParams.limitBig && Number(this.formParams.limitBig) > Number(this.formParams.orderLimitMoney)) {
          this.message.warning('最高减免金额值需小于或等于使用门槛值!');
          this.formParams.limitBig = '';
        }
      }

    }
  }

  /**
   * ----------------------------------------------------------------
   * 审核
   * ----------------------------------------------------------------
   */
  showExamineModal() {
    this.examineParams.remark = '';
    this.isExamineVisible = true;
  }

  // Type 1：通过 7：不通过
  async subExamine(type: number) {
    if (type === 7 && !this.examineParams.remark) {
      this.message.warning('请输入审核意见');
      return
    }
    let params = {
      id: this.routeParams.id,
      reviewRemark: this.examineParams.remark,
      status: type
    }
    this.examineLoading = true;
    const { code, message }: any = await this.services.examineCouponItem(params);
    this.examineLoading = false;

    if (code === 0) {
      this.isExamineVisible = false;
      this.message.success('操作成功');
      this.back();
    } else {
      this.message.error(message);
    }
  }

  /**
   * ----------------------------------------------------------------
   * Other
   * ----------------------------------------------------------------
   */
  couponTypeChange(val: number) {
    this.formParams.limitSmall = '';
    this.formParams.limitBig = '';
  }

  onDateChange(result: any[], kes: string[]) {
    this.formParams[kes[0]] = result.length ? this.datePipe.transform(result[0], 'yyyy-MM-dd HH:mm:ss') : '';
    this.formParams[kes[1]] = result.length ? this.datePipe.transform(result[1], 'yyyy-MM-dd HH:mm:ss') : '';
  }

  // 有效期 Change
  effectiveChange(val: any) {
    this.formParams.limitTimeNum = 0;
    this.formParams.useBeginTime = '';
    this.formParams.useEndTime = '';
    this.effectiveDates = [];
  }

  // is Empty
  isEmpty(val: any) {
    if (val === '' || val === undefined || val === null) {
      return true;
    } else {
      return false;
    }
  }

  // back
  back() {
    history.back();
  }

  // 前端展示
  isShowChange(val: any) {
    if (val == 0) {
      this.formParams.getBeginTime = '';
      this.formParams.getEndTime = '';
      this.receiveDates = [];
    }
  }
}
